$(function () {
    var settings = {
        async: {
            dataType: 'json',
            dataFilter: function (treeId, treeNode, response) {
                if (response.success) {
                    var list = response.entity;
                    if(list!=null && list.length>0){
                        $.each(list,function (index,em) {
                            if(em.status == 2){
                                em.groupName = em.groupName+'(禁用)';
                                list[index] = em;
                            }
                        });
                    }
                    return list;
                } else {
                    icModale(0, response.message);
                }
            },
            enable: true,
            type: 'post',
            url: baseloaction + "/admin/manage/group/ajaxGroupList"
        },
        check: {
            enable: true
        },
        data: {
            key: {
                name: 'groupName',
                title: 'depict',
                status: 'status'
            },
            simpleData: {
                enable: true,
                idKey: 'id',
                pIdKey: 'parentId',
                rootPId: null
            }
        },
        edit: {
            drag: {
                isMove: true
            },
            enable: true,
            removeTitle: function (treeId, treeNode) {
                if (treeNode.isParent) {
                    return "删除：" + treeNode.groupName + '及其子节点';
                } else {
                    return "删除：" + treeNode.groupName;
                }
            },
            renameTitle: function (treeId, treeNode) {
                return "修改：" + treeNode.groupName;
            },
            showRemoveBtn: true,
            showRenameBtn: true
        },
        view: {
            addHoverDom: function (treeId, treeNode) {
                var sObj = $("#" + treeNode.tId + "_span");
                if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
                var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='添加部门' onfocus='this.blur();'></span>";
                sObj.after(addStr);
                var btn = $("#addBtn_" + treeNode.tId);
                if (btn) {
                    btn.bind("click", function () {
                        initUpdateOrAdd(0,treeNode.id);
                    });
                }
                return false;
            },
            removeHoverDom: function (treeId, treeNode) {//鼠标离开删除自定义按钮
                $("#addBtn_" + treeNode.tId).unbind().remove();
            },
            fontCss: function (treeId, treeNode) {
                if (typeof treeNode.highlight == 'undefined' || treeNode.highlight == false) {
                    if(treeNode.status==2){
                        return {color:"#dda525", "font-weight":"normal"};
                    }else{
                        return {color:"#333", "font-weight":"normal"};
                    }
                } else {
                    return {color:"#A60000", "font-weight":"bold"};
                }
            },
            showLine: true,
            selectedMulti: false
        },
        callback: {
            beforeDrop: function (treeId, treeNode, targetNode, moveType, isCopy) {//移动父级节点
                $.ajax({
                    url: baseloaction + '/admin/manage/group/updateSysGroupParentId',
                    data: {'id': treeNode[0].id, 'parentId': targetNode == null ? 0 : targetNode.id},
                    dataType: 'json',
                    success: function (response) {
                        icModale(0, response.message);
                        if (response.success) {//修改成功后移动节点中的数据
                            $.fn.zTree.getZTreeObj('group').moveNode(targetNode, treeNode[0], moveType, false);
                        }
                    },
                    error: function () {
                        icModale(0, '系统错误，移动部门父级归属失败');
                    }
                });
                return false;
            },
            beforeEditName: function (treeId, treeNode) {//点击节点上的修改
                initUpdateOrAdd(treeNode.id,0);
                return false;
            },
            beforeRemove: function (treeId, treeNode) {//点击节点上的删除前
                var ids = getRecursionId(treeNode);
                updateSysGroupStatus(ids, 3);
                return false;
            },
            onAsyncError: function (event, treeId, treeNode, request, status) {
                icModale(0, "系统错误，部门数据列表失败");
            },
            onAsyncSuccess: function (event, treeId, treeNode, msg) {
                var treeObj = $.fn.zTree.getZTreeObj(treeId);
                treeObj.expandAll(true);//展开全部部门
                if ($('#group li').size() == 0) {
                    setNotDataMsg();
                }
                initCount();
            }
        }
    };
    //得到递归的结果
    function getRecursionId(treeNode) {
        var ids = recursionId(treeNode);
        recursionIds='';
        return ids;
    }
    //递归获取节点的所有子级节点的ID串
    var recursionIds = '';
    function recursionId(treeNode) {
        recursionIds +=treeNode.id+",";
        var child = treeNode.children;
        if(child!=null && child.length>0){
            $.each(child,function (index,em) {
                recursionId(em);
            });
        }
        return recursionIds;
    }
    //如果没有专业数据显示
    function setNotDataMsg() {
        $("#group").html('<p><span class="c-4e fs16">亲，还没有部门~~~</span></p>');
    }
    /**
     * 初始化专业/科目数量
     */
    function initCount() {
        var count = getCount("group");
        $('#group-count').html('共' + count + '个部门');
    }
    //初始化权限树
    $.fn.zTree.init($('#group'), settings);

    $('body').on('click', '#delete-group', function () { //批量删除部门
        var nodes = $.fn.zTree.getZTreeObj('group').getCheckedNodes(true);
        nodes = nodes.filter(function (node) {
            return node.check_Child_State ==-1 || node.check_Child_State == 2;
        });
        if (nodes.length == 0) {
            icModale(0, '请选择要删除的部门');
            return;
        }
        var nodeIds = nodes.map(function (node) {
            return node.id;
        }).join(',');

        updateSysGroupStatus(nodeIds, 3);
    }).on('click', '#disable-group', function () {//批量禁用部门
        var nodes = $.fn.zTree.getZTreeObj('group').getCheckedNodes(true);
        if (nodes.length == 0) {
            icModale(0, '请选择要禁用的部门');
            return;
        }
        var nodes = nodes.filter(function (node) {
            return (node.check_Child_State ==-1 || node.check_Child_State == 2)  && node.status == 1;
        });
        if (nodes.length > 0) {
            var nodeIds = nodes.map(function (node) {
                return node.id;
            }).join(',');
            updateSysGroupStatus(nodeIds, 2);
        } else {
            icModale(0, '没有选中处于非禁用状态的部门');
        }
    }).on('click', '#enable-group', function () {//批量恢复部门数据
        var nodes = $.fn.zTree.getZTreeObj('group').getCheckedNodes(true);
        var nodes = nodes.filter(function (node) {
            return (node.check_Child_State ==-1 || node.check_Child_State == 2) && node.status == 2;
        });
        if (nodes.length == 0) {
            icModale(0, '请选择要解禁的部门');
            return;
        }
        var nodeIds = nodes.map(function (node) {
            return node.id;
        }).join(',');
        updateSysGroupStatus(nodeIds, 1);
    }).on('keyup', '#search-group', function () { //搜索部门数据树
        var keyword = this.value;
        var treeObj = $.fn.zTree.getZTreeObj("group");
        if ($.isEmptyObject($.trim(keyword))) {
            var nodes = treeObj.getNodesByFilter(function (node) {
                return node.highlight;
            }, false);
            if (nodes.length > 0) {
                nodes.forEach(function (node) {
                    node.highlight = false;
                    treeObj.updateNode(node);
                });
            }
            return;
        }
        treeObj.getNodesByFilter(function (node) {
            return node.highlight;
        }, false).forEach(function (node) {
            node.highlight = false;
            treeObj.updateNode(node);
        });
        treeObj.getNodesByFilter(function (node) {
            return node.groupName.indexOf(keyword) != -1;
        }).forEach(function (node) {
            node.highlight = true;
            treeObj.updateNode(node);
            treeObj.expandNode(node,true,true,true);
            var parentNode = node.getParentNode();
            if(parentNode!=null){
                treeObj.expandNode(parentNode,true,true,true);
            }
        });
    }).on('click', '#add-group', function () { //添加部门
        initUpdateOrAdd(0,0);
    });

    //全选权限树
    allSelete('all-group', function (status) {
        $.fn.zTree.getZTreeObj("group").checkAllNodes(status);
    });

    /**
     * 添加或修改部门节点
     * @param id 部门ID，修改时传
     * @param parentId 父ID，没有父ID传0
     */
    function initUpdateOrAdd(id,parentId) {
        var title = "修改部门";
        var url = baseloaction + "/admin/manage/group/initUpdate?id="+id;
        var status = false;
        if(id==0){
            title = "新建部门"
            url = baseloaction + "/admin/manage/group/initAdd?parentId="+parentId;
            status = true;
        }
        parent.layer.open({
            type: 2,
            title: '<strong>'+title+'</strong><small class="ml10"></small>',
            shadeClose: false,
            shade: [0.3, '#000000'],
            maxmin: true, //开启最大化最小化按钮
            btn:["确认保存","取消"],
            area: ['900px', '520px'],
            content: url,
            yes: function(index, layero){
                var frame = parent.layer.getChildFrame('body', index);
                var params =frame.find('form').serializeJSON();
                var functionList = frame.find("input[name='functionIds']:checked");
                var functionIds = '';
                if(functionList.length > 0){
                    functionIds = functionList.map(function(){
                        return this.value;
                    }).get().join(",");
                }
                params.functionIds = functionIds;
                params = JSON.stringify(params);
                $.ajax({
                    url: baseloaction +'/admin/manage/group/saveSysGroup',
                    contentType:'application/json;charset=utf-8',
                    type:'post',
                    dataType:'json',
                    data:params,
                    success:function (result) {
                        if(result.success==true){
                            var sysGroup = result.entity;
                            var treeObj = $.fn.zTree.getZTreeObj("group");
                            if(status==false){//修改节点
                                var nodeList = treeObj.getNodesByParam("id",sysGroup.id,null);
                                if(sysGroup.status==1){
                                    nodeList[0].groupName = sysGroup.groupName;
                                }else{
                                    nodeList[0].groupName = sysGroup.groupName+'(禁用)';
                                }
                                nodeList[0].status = sysGroup.status;
                                treeObj.updateNode(nodeList[0]);
                            }else{//添加节点
                                var parentId = result.parentId;
                                var parentNode = null;
                                if(parentId!=null){
                                    var nodeList = treeObj.getNodesByParam("id",parentId,null);
                                    if(nodeList!=null && nodeList.length > 0){
                                        parentNode = nodeList[0];
                                    }
                                }
                                var nodes = new Array();
                                nodes.push(sysGroup);
                                treeObj.addNodes(parentNode,nodes);
                                //重新初始化节点数量
                                initCount();
                                $("#not-data-msg").remove();
                            }
                            parent.layer.close(index);
                        }else{
                            icModale(0, result.message);
                        }
                    },
                    error:function (error) {
                        icModale(0, "系统错误，保存部门数据失败");
                    }
                });
            }
        });
    }


    /**
     * 修改部门状态
     * @param groupIds 部门ID串
     * @param status 状态，1正常，2禁用，3删除
     * @return {boolean}
     */
    function updateSysGroupStatus(groupIds, status) {
        var tips = '';
        if (status == 1) {
            tips = '确认解禁选中的部门？';
        } else if (status == 2) {
            tips = '确认禁用选中的部门？';
        } else if (status == 3) {
            tips = '确认删除选中的部门？';
        }
        icModale(2, tips, 3, function () {
            $.ajax({
                url: baseloaction + '/admin/manage/group/updateSysGroupStatus',
                type:'post',
                data: {'ids': groupIds, 'status': status},
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        icModale(0, response.message);
                        var zTree = $.fn.zTree.getZTreeObj('group');
                        var arr = (groupIds+"").split(",");
                        $.each(arr,function (index , nodeId) {
                            if(nodeId!=null && $.trim(nodeId)!=''){
                                var node = zTree.getNodeByParam('id', nodeId, null);
                                node.status = status;
                                if(status == 1 || status == 2){
                                    if(status==1){
                                        node.groupName = node.groupName.replace(/\(禁用\)/g,'');
                                    }
                                    if(status ==2){
                                        node.groupName = node.groupName+'(禁用)';
                                    }
                                    zTree.updateNode(node);
                                }
                                if(status == 3){
                                    zTree.removeNode(node);
                                    var count = getCount("group");
                                    if(count<=0){
                                        setNotDataMsg();
                                    }
                                    initCount();
                                }
                            }
                        });
                    } else {
                        icModale(0, response.message);
                    }
                },
                error: function (error) {
                    icModale(0, "系统错误，部门数据操作失败");
                }
            });
        });
        return true;
    }
});